<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import AppHeader from "@/components/app_header.vue";
import AppBind from "@/components/app_bind.vue";
import { useConfigStore } from "@/store/modules/config";
import { encryptAddress } from "@/utils";
import { showSuccessToast, showToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import Decimal from "decimal.js";
import { isMobileDevice } from "@/utils/base_index";

const useConfig = useConfigStore();
const route = useRoute();

const { locale, t } = useI18n();
const isShow = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = reactive([]);
const isFocus = ref(false); //输入状态

const router = useRouter();

const ToBlack = () => {
  router.push("transaction");
};

/// ======================bigv

const amount = ref();

const usdtAmount = ref(0);
const checkingUSDT = async () => {
  const amount = await useConfig.ALLOWANCE_USDT();
  console.log("授权额度 amount", amount);
  // if (amount < 10000) {
  //   allowance();
  //   return;
  // }
  usdtAmount.value = amount;
};

const orderInfo = reactive({
  sellAddress: "", // 地址
  price: 0, // 单价
  inCptAmount: 0, // 数量
  outCptAmount: 0 //
});
const loadData = async () => {
  const res = await useConfig.masterContract.methods
    .getTradeCurrent(route.query.address)
    .call();
  console.log(res);
  const { sellAddress, price, inCptAmount, outCptAmount } = res;
  orderInfo.sellAddress = sellAddress;
  orderInfo.price = useConfig.web3.utils.fromWei(price, "ether");
  orderInfo.inCptAmount = useConfig.web3.utils.fromWei(inCptAmount, "ether");
  orderInfo.outCptAmount = useConfig.web3.utils.fromWei(outCptAmount, "ether");
};

// 限额
const quota = computed(() => {
  return Decimal(orderInfo.inCptAmount).sub(Decimal(orderInfo.outCptAmount));
});
// 支出
const expenditure = computed(() => {
  const _amount = amount.value || 0;
  return Decimal(_amount).mul(Decimal(orderInfo.price));
});
// 接收
const receive = computed(() => {
  if (!amount.value) {
    return "--";
  }
  return amount.value;
});
// 是否输入了数量
const isAuantityEmpty = computed(() => {
  return !Boolean(Number(amount.value));
});

const allowance = async () => {
  console.log("授权");

  // 先检查一遍授权 如果额度足够 就不用授权了
  // await checkingUSDT();
  // if (usdtAmount.value > 0) {
  //   return;
  // }

  const amount = useConfig.web3.utils.toWei(100000000, "ether");
  const data = useConfig.usdtContract.methods
    .approve(useConfig.masterContractAddress, amount)
    .encodeABI();
  const params = {
    to: useConfig.usdtContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      checkingUSDT();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });
};

const buy = async () => {
  if (isAuantityEmpty.value) return;
  const _quota = quota.value;
  const _amount = Number(amount.value ?? 0);

  // 如果卖方地址 === 我的地址 锁
  if (
    orderInfo.sellAddress?.toLocaleUpperCase() ===
    useConfig.account?.toLocaleUpperCase()
  ) {
    return;
  }

  // 验证输入框与限额
  if (_amount < 1 || _amount > _quota) return;
  const usdtBalance = Number(useConfig.usdtBalance);
  // 验证支付余额
  if (expenditure.value > usdtBalance) return;

  const _amountWei = useConfig.web3.utils.toWei(_amount, "ether");
  const data = useConfig.masterContract.methods
    .buy(route.query.address, _amountWei)
    .encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      loadData();
      amount.value = null;
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("购买");
};

onMounted(() => {
  loadData();
  checkingUSDT();
});
</script>

<template>
  <div class="home div-container">
    <!-- header--start-->
    <div class="div-header">
      <div class="div-left" @click.stop="ToBlack">
        <img src="@/assets/icon-black.png" alt="" />
      </div>
      <span class="title">
        <img src="@/assets/icon-logo.png" width="40" alt="" />
      </span>
      <div class="div-right">...</div>
    </div>
    <!-- header--start-->
    <!-- div-wallet--start-->
    <AppHeader />
    <!--    <div class="div-wallet">-->
    <!--      <div class="wallet" @click.stop="showDialog">-->
    <!--        <img src="@/assets/icon-wallet.png" width="32" height="32" alt="" />-->
    <!--        {{ useConfig.getEncryptAccount }}-->
    <!--      </div>-->
    <!--      <div class="div-change" @click="changeLang">-->
    <!--        <img src="@/assets/icon-change.png" width="19" height="19" alt="" />-->
    <!--        {{ $t("home.ch") }}-->
    <!--      </div>-->
    <!--    </div>-->

    <div class="div-record">
      <div class="div-record-title">{{ $t("exchange.buy") }}</div>
      <div class="div-list">
        <van-list>
          <van-cell>
            <span>
              <img
                src="./../../assets/icon-exchange-price.png"
                width="19"
                alt=""
              />
              {{ orderInfo.price }} USDT
            </span>
            <span>{{ $t("exchange.price") }}</span>
          </van-cell>
          <van-cell>
            <span>
              <img
                src="./../../assets/icon-exchange-quantity.png"
                width="19"
                alt=""
              />
              {{ orderInfo.inCptAmount }} {{ useConfig.name }}
            </span>
            <span>{{ $t("exchange.quantity") }}</span>
          </van-cell>
          <van-cell class="margin-bottom-0">
            <span>
              <img
                src="./../../assets/icon-exchange-address.png"
                width="19"
                alt=""
              />
              {{ encryptAddress(orderInfo.sellAddress) }}
            </span>
            <span>{{ $t("exchange.address") }}</span>
          </van-cell>
        </van-list>
      </div>
    </div>
    <!--购买ESC -->
    <div class="div-record">
      <div class="div-list div-buy-list">
        <div class="div-buy-title">{{ $t("exchange.buy") }}CPT</div>
        <van-list>
          <van-cell>
            <span>
              <img
                src="./../../assets/icon-exchange-blance.png"
                width="19"
                alt=""
              />
              {{ useConfig.usdtBalance }} USDT
            </span>
            <span>{{ $t("exchange.blance") }}</span>
          </van-cell>

          <div class="div-quantity">
            <p class="div-quantity-title">{{ $t("exchange.quantity") }}</p>
            <div>
              <van-field
                v-model="amount"
                type="digit"
                class="enterAddress"
                :max="parseFloat(quota)"
                :class="isFocus ? 'focus-style' : ''"
                :placeholder="$t('transaction.pleaseEnterQuantity')"
                @focus="isFocus = true"
                @blur="isFocus = false"
              />
              <span class="div-all" @click="amount = quota">{{
                $t("exchange.all")
              }}</span>
            </div>
          </div>

          <div class="div-limit">
            <span>{{ $t("exchange.quota") }}</span>
            <span>{{ quota }} {{ useConfig.name }}</span>
          </div>

          <van-cell>
            <span :class="{ 'font-gold': !isAuantityEmpty }">
              {{ !isAuantityEmpty ? expenditure + " USDT" : "--" }}
            </span>
            <span>{{ $t("exchange.expenditure") }}</span>
          </van-cell>

          <van-cell class="margin-bottom-0">
            <span :class="{ 'font-gold': !isAuantityEmpty }">
              {{ !isAuantityEmpty ? receive + " " + useConfig.name : "--" }}
            </span>
            <span>{{ $t("exchange.receive") }}</span>
          </van-cell>
        </van-list>
      </div>
    </div>
    <div
      v-if="usdtAmount > 0"
      class="div-btn div-buy-btn"
      :class="
        orderInfo.sellAddress?.toLocaleUpperCase() ===
          useConfig.account?.toLocaleUpperCase() ||
        isAuantityEmpty ||
        quota < amount
          ? 'btn-disabled'
          : ''
      "
      @click="buy"
    >
      {{ $t("exchange.buy") }}
    </div>

    <div
      v-if="usdtAmount < 1000"
      class="div-btn div-auth-btn"
      @click="() => allowance()"
    >
      {{ $t("exchange.auth") }}
    </div>
  </div>
</template>

<style scoped lang="less">
@import "./../../styles/mixin.less";
p {
  margin: 0px;
}
.home {
  font-size: 14px;
  color: #ffffff;
  padding-bottom: 20px;
}

.div-wallet {
  height: 44px;
  padding: 0 14px;
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  & > div {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .wallet {
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 20px;
    border: 1px solid #9cb3bf;
  }
}
.div-record {
  padding: 20px 14px;
  position: relative;
  &-title {
    font-weight: 500;
    font-size: 23px;
    color: #e5f0f4;
    line-height: 40px;
    text-indent: 14px;
    position: relative;
    margin-bottom: 18px;
    &:before {
      display: block;
      content: "";
      width: 5px;
      height: 23px;
      position: absolute;
      left: 0px;
      top: 8px;
      background: radial-gradient(
        132% 97% at 11% 76%,
        #c172ff 0%,
        #c172ff 0%,
        #08e6f8 100%
      );
      border-radius: 5px;
    }
  }

  .div-list {
    padding: 32px 22px;
    background: #27283e;
    border-radius: 20px;
    border: 1px solid #47ddc2;
    opacity: 0.99;
    .div-buy-title {
      font-weight: 500;
      font-size: 18px;
      color: #e5f0f4;
      padding-bottom: 20px;
    }
    :deep(.van-cell) {
      background: #2e2f4a;
      color: #e5f0f4;
      height: 50px;
      margin-bottom: 18px;
    }
    .margin-bottom-0 {
      margin-bottom: 0;
    }
    :deep(.van-cell:after) {
      display: none;
    }
    :deep(.van-cell__value) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span:nth-child(1) {
        font-weight: 500;
        font-size: 14px;
        color: #fff;
        line-height: 20px;
        display: flex;
        align-items: center;
        gap: 6px;
      }
      span:nth-child(2) {
        font-size: 12px;
        color: #606374;
        font-weight: 500;
      }
    }
    .font-gold {
      color: #ff8f6e !important;
    }
  }
  .div-buy-list {
    border: 1px solid #62737f;
  }
  .div-quantity {
    position: relative;
    .div-quantity-title {
      font-weight: 500;
      font-size: 12px;
      color: #606374;
      line-height: 16px;
    }
    .enterAddress {
      font-weight: 500;
      font-size: 14px;
      color: #e5f0f4;
      line-height: 20px;
      background-color: #27283e;
      padding-left: 0px;
      padding-right: 0px;
      :deep(.van-field__control) {
        color: #fff;
      }
    }
    :deep(.van-cell:after) {
      left: 0px;
    }
    :deep(.van-field) {
      margin: 0 auto 16px;
      border-bottom: 1px solid #e5f0f4;
      padding-left: 0px;
      background: none;
      .van-field__control {
        color: #fff;
        font-size: 14px;
      }
      &.focus-style {
        border-bottom: 1px solid #0064fb;
      }
    }
    .div-all {
      position: absolute;
      right: 0px;
      bottom: 10px;
      color: #47ddc2;
    }
  }
}
.div-limit {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 500;
  font-size: 14px;
  color: #e5f0f4;
  line-height: 20px;
  padding-bottom: 20px;
  span:nth-child(1) {
    color: #606374;
  }
}
.div-buy-btn {
  margin: 0 12px 10px;
  display: flex;
  align-items: center;
  width: calc(100% - 24px);
  justify-content: center;
  height: 56px;
  font-size: 16px;
  color: #fff;
  border-radius: 16px;
  background: #0066ff;
  &.btn-disabled {
    background-color: #3e436c;
    color: #5e6486;
  }
}
.div-auth-btn {
  margin: 0 12px 10px;
  display: flex;
  align-items: center;
  width: calc(100% - 24px);
  justify-content: center;
  height: 56px;
  font-size: 16px;
  color: #151d24;
  font-weight: 500;
  border-radius: 16px;
  background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
}
</style>
